/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.util;

import java.awt.Desktop;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author SDS
 */
public class HttpUtil {

    public static String getPageContents( String url, String charsetName ) {
        return getPageContents( url, null, charsetName );
    }

    public static String getPageContents( String url, Hashtable param, String charsetName ) {

        HttpURLConnection connHttp = null;

        StringBuilder sb = new StringBuilder();

        if( charsetName == null || "".equals(charsetName) ) {
            charsetName = "EUC-KR";
        }

        try {

            URL connUrl = new URL( url );

            connHttp = (HttpURLConnection) connUrl.openConnection();

            connHttp.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded;" );

            connHttp.setDoOutput(true);
            connHttp.setDoInput(true);

            // 헤더 셋팅
            connHttp.setRequestProperty( "Accept","*/*" );
            connHttp.setRequestProperty( "Accept-Charset","EUC-KR,utf-8;" );
            connHttp.setRequestProperty( "User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; ko; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8" );

            // 파라미터 설정
            if( param != null && ! param.isEmpty() ) {

                String key = null;
                String urlParam = "";
                for( Enumeration e = param.keys() ; e.hasMoreElements(); ) {
                    key = (String) e.nextElement();
                    urlParam += key + "=" + (String) param.get(key) + "&";
                }

                OutputStream out = connHttp.getOutputStream();
                out.write( urlParam.getBytes(charsetName) );
                out.flush();
                out.close();

            }

            // 페이지 읽기
            BufferedReader buf = new BufferedReader( new InputStreamReader(connHttp.getInputStream(), charsetName) );
            String readLine;
            while( (readLine = buf.readLine()) != null) {
                readLine.trim();
                sb.append(readLine).append("\r\n");

            }

        } catch (IOException ex) {
            Log.error( ex );
        } finally {
            if( connHttp != null ) connHttp.disconnect();
        }

        return sb.toString();

    }

    
    public static Vector<String[]> getTr( String pageText, String pattern ) {

        Vector<String[]> result = new Vector<String[]>();

        Pattern regex = Pattern.compile("<\\s*tr\\s*" + pattern + ".*?>(.*?)<\\s*/\\s*tr\\s*>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
        Matcher matcher = regex.matcher( pageText );

        while( matcher.find() ) {
            result.add( getTd(matcher.group(1)) );
        }

        return result;

    }

    
    public static String[] getTd( String pageText ) {

        ArrayList result = new ArrayList();

        Pattern p;
        Matcher m;

        pageText = pageText.trim();

        p = Pattern.compile(">\\s+?<", Pattern.DOTALL );
        m = p.matcher( pageText );
        pageText = m.replaceAll( "><" );

        p = Pattern.compile("<\\s*/\\s*td\\s*>", Pattern.CASE_INSENSITIVE );
        m = p.matcher( pageText );
        pageText = m.replaceAll( "</td>" );

        p = Pattern.compile("</td>$" );
        m = p.matcher( pageText );
        pageText = m.replaceAll( "" );

        p = Pattern.compile("<\\s*td.*?>", Pattern.CASE_INSENSITIVE );
        m = p.matcher( pageText );
        pageText = m.replaceAll( "" );

        return pageText.split( "</td>" );

    }

    /**
     * 속성 항목의 값을 가져온다.
     *
     * getAttrValue( "href", "<a href="gggg" />" );
     * --> gggg
     *
     * @param attr 추출할 속성명
     * @param htmlText 추출대상 텍스트
     * @return 속성값
     */
    public static String getAttrValue( String attr, String htmlText ) {

        String result = "";

        Pattern regex = Pattern.compile( attr + "\\s*=\\s*\"(.*?)\"", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE );
        Matcher matcher = regex.matcher( htmlText );

        if( matcher.find() ) {
            result = matcher.group( 1 );
        }

        return result;

    }

    public static String getInnerHTML( String htmlText ) {

        String result = "";

        Pattern regex = Pattern.compile( ">(.*?)<" );
        Matcher matcher = regex.matcher( htmlText );

        if( matcher.find() ) {
            result = matcher.group( 1 );
        }

        return result;

    }


    public static String removeScript( String pageText ) {

        Pattern regex = Pattern.compile( "<\\s*[s|S][c|C][r|R][i|I][p|P][t|T].*?>.*?<\\s*/\\s*[s|S][c|C][r|R][i|I][p|P][t|T]\\s*>", Pattern.DOTALL );
        Matcher matcher = regex.matcher( pageText );

        return matcher.replaceAll( "" );

    }

    /**
     * 특정 인터넷 주소를 기본 브라우저로 연다.
     * @param url 인터넷주소
     * @return 작업성공여부
     */
    public static boolean openBrowser( String url ){

        if( !Desktop.isDesktopSupported() ) return false;

        Desktop deskTop = Desktop.getDesktop();

        if( !deskTop.isSupported(Desktop.Action.BROWSE) ) return false;

        try {

            URI uri = new URI( url );
            deskTop.browse( uri );

        } catch ( Exception e ) {

            Log.error( e );
            return false;

        }

        return true;

    }

}
